﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Data;
using Suzsoft.Smart.Data;

using ESOL.Common.Entity;
using ESOL.Business.Fa;
using ESOL.Common.DTO;
using ESOL.Business.Mst;
using ESOL.Common;
using BPM.Foundation.PWDB;
using BPM.Base.Tools;

namespace ESOL.Services
{
    [ServiceBehavior(UseSynchronizationContext = false,
    ConcurrencyMode = ConcurrencyMode.Multiple,
    InstanceContextMode = InstanceContextMode.PerCall)]
    public class FaService : IFaService
    {
        public bool TestConnect()
        {
            return true;
        }

        public FaAssetsTypeEntity GetFaAssetsTypeByKey(string id)
        {
            try
            {
                return DataAccess.SelectSingle<FaAssetsTypeEntity>(new FaAssetsTypeEntity { Id = id });
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        public FaAssetsEntity GetFaAssetByKey(string id)
        {
            try
            {
                return DataAccess.SelectSingle<FaAssetsEntity>(new FaAssetsEntity { Id = id });
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        public bool SaveFaAsset(string userNo, FaAssetsEntity asset)
        {
            try
            {
                if (asset == null)
                    return false;
                FaAssetsEntity cur = DataAccess.SelectSingle<FaAssetsEntity>(new FaAssetsEntity { Id = asset.Id });
                if (cur == null)
                {
                    FaAssetsTypeEntity type = DataAccess.SelectSingle<FaAssetsTypeEntity>(new FaAssetsTypeEntity { Id = cur.AssetTypeId });
                    if (type == null || string.IsNullOrEmpty(type.AssetTypeCode))
                    {
                        MyDebug.write("固定资产类型不能为空！");
                        return false;
                    }
                    asset.AssetCode = FaAssetsBs.GetNextAssetCode(type.AssetTypeCode);
                    asset.CreatedBy = userNo;
                    asset.CreatedDate = DateTime.Now;
                    asset.UpdatedBy = userNo;
                    asset.UpdatedDate = DateTime.Now;
                    asset.IsActive = 1;
                    return DataAccess.Insert(asset);
                }
                else
                {
                    asset.UpdatedBy = userNo;
                    asset.UpdatedDate = DateTime.Now;
                    return DataAccess.Update(asset);
                }
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return false;
            }
        }

        public List<FaAssetsEntity> GetAllChildAssets(FaAssetsEntity asset)
        {
            List<FaAssetsEntity> listChild = new List<FaAssetsEntity>();
            GetAllChildAssets(asset, listChild);
            return listChild;
        }
        private void GetAllChildAssets(FaAssetsEntity asset, List<FaAssetsEntity> list)
        {
            if (list.Count == 0)
            {
                list.Add(asset);
            }
            List<FaAssetsEntity> listChild = DataAccess.Select<FaAssetsEntity>(new FaAssetsEntity { ParentAsset = asset.Id });
            if (listChild != null && listChild.Count > 0)
            {
                foreach (FaAssetsEntity at in listChild)
                {
                    list.Add(at);
                    GetAllChildAssets(at, list);
                }
            }
        }

        public System.Data.DataSet GetFaRepairHisAllDsByAssetId(string assetId)
        {
            try
            {
                string sql = @"SELECT A.*,H.*
                            FROM FA_ASSETS A
                            INNER JOIN FA_REPAIR_HISTORY H ON H.ASSET_ID = A.ID
                            WHERE A.ASSET_ID = '" + assetId + "' ORDER BY REPAIR_DATE DESC";
                return DataAccess.SelectDataSet(sql);
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        public System.Data.DataSet GetFaManufactureHisAllDsByAssetId(string assetId)
        {
            try
            {
                string sql = @"SELECT A.*,H.*
                            FROM FA_ASSETS A
                            INNER JOIN FA_MANUFACTURER_HISTORY H ON H.ASSET_ID = A.ID
                            WHERE A.ASSET_ID = '" + assetId + "' ORDER BY MAINTAIN_DATE DESC";
                return DataAccess.SelectDataSet(sql);
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        public System.Data.DataSet GetFaUsedHisAllDsByAssetId(string assetId)
        {
            try
            {
                string sql = @"SELECT A.*,H.*,C.ITEM_NAME AS USED_TYPE_NAME, D.DEPARTMENT_NAME, P.NAME_CN AS PERSON_NAME
                            FROM FA_ASSETS A
                            INNER JOIN FA_USED_HISTORY H ON H.ASSET_ID = A.ASSET_ID
							LEFT JOIN MST_COMMON_ITEM C ON C.ITEM_CODE = H.USED_TYPE
							LEFT JOIN MST_DEPARTMENT D ON D.DEPARTMENT_ID = H.DEPARTMENT_ID
							LEFT JOIN MST_PERSON P ON P.PERSON_ID = H.PERSON_ID
                            WHERE A.ASSET_ID = '" + assetId + "' ORDER BY FROM_DATE DESC";
                return DataAccess.SelectDataSet(sql);
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        //固定资产保养
        public FaManufacturerEntity GetFaManufacturerByKey(string id)
        {
            try
            {
                return DataAccess.SelectSingle<FaManufacturerEntity>(new FaManufacturerEntity { Id = id });
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        //保存固定资产保养
        public bool SaveFaManufacturer(string userNo, FaManufacturerEntity entity)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    FaManufacturerEntity cur = DataAccess.SelectSingle<FaManufacturerEntity>(new FaManufacturerEntity { Id = entity.Id });
                    //更新固定资产的下次保养日期
                    FaAssetsEntity fa = DataAccess.SelectSingle<FaAssetsEntity>(new FaAssetsEntity { Id = entity.Id });
                    //增加一笔保养历史
                    FaManufacturerHistoryEntity history = new FaManufacturerHistoryEntity();
                    history.Id = Guid.NewGuid().ToString();
                    history.AssetId = entity.Id;
                    history.MaintainItem = entity.LastMaintainItem;
                    history.MaintainDate = entity.LastMaintainDate;
                    history.MaintainCompany = entity.LastMaintainCompany;
                    history.MaintainPerson = entity.LastMaintainPerson;
                    history.MaintainFee = entity.LastMaintainFee;
                    history.Remark = entity.Remark;

                    broker.BeginTransaction();
                    if (cur == null)
                    {
                        DataAccess.Insert(entity, broker);
                    }
                    else
                    {
                        DataAccess.Update(entity, broker);
                    }
                    DataAccess.Insert(history, broker);
                    if (fa != null)
                    {
                        fa.NextMaintainDate = entity.NextMaintainDate;
                        fa.NextMaintainItem = entity.NextMaintainItem;
                        DataAccess.Update(fa, broker);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    MyDebug.write(ex.Message);
                    return false;
                }
            }

        }

        //分页查询固定资产
        public System.Data.DataSet GetFaAssetsAllDsByCondition(AssetQueryCondition con)
        {
            int pageIndex = 1;
            int pageSize = 50;
            if (con.txtPageIndex != 0)
                pageIndex = con.txtPageIndex;
            if (con.txtPageSize != 0)
                pageSize = con.txtPageSize;
            string condition = "";
            if (!string.IsNullOrEmpty(con.AssetTypeId))
            {
                condition += " AND (AT1.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT2.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT3.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT4.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT5.ASSET_TYPE_ID = '" + con.AssetTypeId + "') ";
            }
            else if (!string.IsNullOrEmpty(con.Status))
            {
                condition += " AND FA.STATUS = '" + con.Status + "' ";
            }
            condition += " and cfg.IS_ACTIVE=" + con.IsActive;
            if (!string.IsNullOrEmpty(con.AssetCode))
            {
                condition += " AND FA.ASSET_CODE LIKE '%" + con.AssetCode + "%' ";
            }
            if (!string.IsNullOrEmpty(con.AssetSpec))
            {
                condition += " AND FA.ASSET_SPEC = '" + con.AssetSpec + "' ";
            }
            if (!string.IsNullOrEmpty(con.AssetName))
            {
                condition += " AND FA.ASSET_NAME LIKE '%" + con.AssetName + "%' ";
            }

            string sql = "";
            if (string.IsNullOrEmpty(condition))
            {
                string sqlSource = @"select top {0} *,(select count(1) from FA_ASSETS) as cnt
from FA_ASSETS
where id not in (
    select top ({1}*({2}-1)) id from FA_ASSETS order by created_date desc
) order by created_date desc";
                sqlSource = string.Format(sqlSource, pageSize, pageSize, pageIndex);
                sql = @"select FA.*, CASE WHEN FA.NEED_MAINTENANCE = 1 THEN '需要保养' ELSE '' END AS NEED_MAINTAIN,
AT1.ASSET_TYPE_CODE AS ASSET_TYPE_CODE1, AT1.ASSET_TYPE_NAME AS ASSET_TYPE_NAME1,
AT2.ASSET_TYPE_CODE AS ASSET_TYPE_CODE2, AT2.ASSET_TYPE_NAME AS ASSET_TYPE_NAME2,
AT3.ASSET_TYPE_CODE AS ASSET_TYPE_CODE3, AT3.ASSET_TYPE_NAME AS ASSET_TYPE_NAME3,
AT4.ASSET_TYPE_CODE AS ASSET_TYPE_CODE4, AT4.ASSET_TYPE_NAME AS ASSET_TYPE_NAME4,
AT5.ASSET_TYPE_CODE AS ASSET_TYPE_CODE5, AT5.ASSET_TYPE_NAME AS ASSET_TYPE_NAME5
from ({0}) FA
LEFT JOIN FA_ASSETS_TYPE AT1 ON AT1.ID = FA.ASSET_TYPE_ID
LEFT JOIN FA_ASSETS_TYPE AT2 ON AT2.ID = AT1.PARENT_ID
LEFT JOIN FA_ASSETS_TYPE AT3 ON AT3.ID = AT2.PARENT_ID
LEFT JOIN FA_ASSETS_TYPE AT4 ON AT4.ID = AT3.PARENT_ID
LEFT JOIN FA_ASSETS_TYPE AT5 ON AT5.ID = AT4.PARENT_ID";
                sql = string.Format(sql, sqlSource);
            }
            else
            {
                sql = @"select top {0} *,(select count(1) from ({3}) t) as cnt
from ({3}) t
where t.id not in (
    select top ({1}*({2}-1)) id from ({3}) t order by created_date desc
) order by created_date desc";
                string sqlSource = @"select FA.*, CASE WHEN FA.NEED_MAINTENANCE = 1 THEN '需要保养' ELSE '' END AS NEED_MAINTAIN,
AT1.ASSET_TYPE_CODE AS ASSET_TYPE_CODE1, AT1.ASSET_TYPE_NAME AS ASSET_TYPE_NAME1,
AT2.ASSET_TYPE_CODE AS ASSET_TYPE_CODE2, AT2.ASSET_TYPE_NAME AS ASSET_TYPE_NAME2,
AT3.ASSET_TYPE_CODE AS ASSET_TYPE_CODE3, AT3.ASSET_TYPE_NAME AS ASSET_TYPE_NAME3,
AT4.ASSET_TYPE_CODE AS ASSET_TYPE_CODE4, AT4.ASSET_TYPE_NAME AS ASSET_TYPE_NAME4,
AT5.ASSET_TYPE_CODE AS ASSET_TYPE_CODE5, AT5.ASSET_TYPE_NAME AS ASSET_TYPE_NAME5
from FA_ASSETS FA
LEFT JOIN FA_ASSETS_TYPE AT1 ON AT1.ID = FA.ASSET_TYPE_ID
LEFT JOIN FA_ASSETS_TYPE AT2 ON AT2.ID = AT1.PARENT_ID
LEFT JOIN FA_ASSETS_TYPE AT3 ON AT3.ID = AT2.PARENT_ID
LEFT JOIN FA_ASSETS_TYPE AT4 ON AT4.ID = AT3.PARENT_ID
LEFT JOIN FA_ASSETS_TYPE AT5 ON AT5.ID = AT4.PARENT_ID
where 1=1 ";
                sqlSource += condition;
                sql = string.Format(sql, pageSize, pageSize, pageIndex, sqlSource);
            }
            try
            {
                return DataAccess.SelectDataSet(sql);
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }


        //固定资产维修记录
        public FaRepairEntity GetFaRepairByKey(string id)
        {
            try
            {
                return DataAccess.SelectSingle<FaRepairEntity>(new FaRepairEntity { Id = id });
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        //固定资产维修记录保存
        public bool SaveFaRepair(string userNo, FaRepairEntity entity)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    //增加一笔保养历史
                    FaRepairHistoryEntity history = new FaRepairHistoryEntity();
                    history.Id = Guid.NewGuid().ToString();
                    history.AssetId = entity.Id;
                    history.Reason = entity.Reason;
                    history.RepairDate = entity.LastRepairDate;
                    history.RepairCompany = entity.LastRepairCompany;
                    history.RepairPerson = entity.LastRepairPerson;
                    history.Result = entity.Result;
                    history.RepairFee = entity.RepairFee;
                    history.Remark = entity.Remark;

                    FaRepairEntity cur = DataAccess.SelectSingle<FaRepairEntity>(new FaRepairEntity { Id = entity.Id });
                    broker.BeginTransaction();
                    if (cur == null)
                    {
                        DataAccess.Insert(entity, broker);
                    }
                    else
                    {
                        DataAccess.Update(entity, broker);
                    }
                    DataAccess.Insert(history, broker);
                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    MyDebug.write(ex.Message);
                    return false;
                }
            }

        }


        public bool CheckTypeCode(string code, string typeId)
        {
            string sql = "";
            if (string.IsNullOrEmpty(typeId))
            {
                sql = "SELECT * FROM FA_ASSETS_TYPE WHERE ASSET_TYPE_CODE = '" + code + "'";
            }
            else
            {
                sql = "SELECT * FROM FA_ASSETS_TYPE WHERE ASSET_TYPE_CODE = '" + code + "' AND ID != '" + typeId + "'";
            }
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return false;
            }
            return true;
        }

        public bool SaveFaAssetType(string userNo, FaAssetsTypeEntity entity)
        {
            try
            {
                if (entity == null)
                    return false;
                FaAssetsTypeEntity cur = DataAccess.SelectSingle<FaAssetsTypeEntity>(new FaAssetsTypeEntity { Id = entity.Id });
                if (cur == null)
                {
                    entity.CreatedBy = userNo;
                    entity.CreatedDate = DateTime.Now;
                    entity.UpdatedBy = userNo;
                    entity.UpdatedDate = DateTime.Now;
                    entity.IsActive = 1;
                    return DataAccess.Insert(entity);
                }
                else
                {
                    entity.UpdatedBy = userNo;
                    entity.UpdatedDate = DateTime.Now;
                    return DataAccess.Update(entity);
                }
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return false;
            }
        }



        public List<FaAssetsTypeEntity> GetFaAssetsTypeAllList()
        {
            try
            {
                return DataAccess.SelectAll<FaAssetsTypeEntity>();
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        //保存固定资产使用申请
        public bool SaveFaAssetApp(string userNo, FaUsedApplicationEntity entity)
        {
            try
            {
                FaUsedApplicationEntity cur = DataAccess.SelectSingle<FaUsedApplicationEntity>(new FaUsedApplicationEntity { Id = entity.Id });
                if (cur == null)
                {
                    entity.ApplicationCode = MstCodeRuleBs.GetCurrentOrderCode("AssetUsedApplication");
                    return DataAccess.Insert(entity);
                }
                else
                {
                    return DataAccess.Update(entity);
                }
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return false;
            }
        }

        //审核固定资产使用申请
        public bool ApproveFaUseApp(string userNo, FaUsedApplicationEntity app)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    if (app.Status == "FUA03")//已拒绝
                    {
                        DataAccess.Update(app, broker);
                    }
                    else if (app.Status == "FUA02")//已审核
                    {
                        DataAccess.Update(app, broker);
                    }
                    else if (app.Status == "FUA04")//已发货
                    {
                        if (string.IsNullOrEmpty(app.AssetId))
                        {
                            broker.RollBack();
                            throw new Exception("请先选择一个固定资产！");
                        }
                        DataAccess.Update(app, broker);
                        //修改固定资产的状态
                        FaAssetsEntity asset = DataAccess.SelectSingle<FaAssetsEntity>(new FaAssetsEntity { Id = app.AssetId });
                        switch (app.UsedType)
                        {
                            case "UT01":
                                asset.Status = "FAS02";
                                break;
                            case "UT02":
                                asset.Status = "FAS01";
                                break;
                            case "UT03":
                                asset.Status = "FAS02";
                                break;
                            case "UT04":
                                asset.Status = "FAS03";
                                break;
                            case "UT05":
                                asset.Status = "FAS04";
                                break;
                        }
                        DataAccess.Update(asset, broker);
                        //修改固定资产的使用情况
                        FaUsedEntity used = DataAccess.SelectSingle<FaUsedEntity>(new FaUsedEntity { Id = app.AssetId });
                        bool isNew = false;
                        if (used == null || string.IsNullOrEmpty(used.Id))
                        {
                            used = new FaUsedEntity();
                            used.Id = app.AssetId;
                            isNew = true;
                        }
                        used.ApplicationId = app.Id;
                        used.DepartmentId = app.DepartmentId;
                        used.PersonId = app.PersonId;
                        used.FromDate = app.FromDate;
                        used.EndDate = app.EndDate;
                        used.Remark = app.Remark;
                        if (isNew)
                        {
                            DataAccess.Insert(used, broker);
                        }
                        else
                        {
                            DataAccess.Update(used, broker);
                        }
                        //更新历史记录
                        FaUsedHistoryEntity history = new FaUsedHistoryEntity();
                        history.Id = Guid.NewGuid().ToString();
                        history.AssetId = app.AssetId;
                        history.ApplicationId = app.Id;
                        history.UsedType = app.UsedType;
                        history.DepartmentId = app.DepartmentId;
                        history.PersonId = app.PersonId;
                        history.FromDate = app.FromDate;
                        //history.EndDate = app.EndDate;
                        history.Remark = app.Remark;
                        DataAccess.Insert(history, broker);
                    }
                    else if (app.Status == "FUA05")//已确认
                    {
                        DataAccess.Update(app, broker);
                    }

                    broker.Commit();
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
            return true;
        }
        

        public FaSaleAssetsEntity GetFaSaleAssetByKey(string id)
        {
            try
            {
                return DataAccess.SelectSingle<FaSaleAssetsEntity>(new FaSaleAssetsEntity { Id = id });
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

        /// 1：设置固定资产状态为变卖状态
        /// 2：增加一笔历史记录
        /// 3：更改固定资产所属情况
        public bool SaleAsset(FaAssetsEntity asset, FaSaleAssetsEntity salesInfo, bool isNew)
        {
            FaUsedEntity used = DataAccess.SelectSingle<FaUsedEntity>(new FaUsedEntity { Id = asset.Id });
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();

                    //设置固定资产状态为已变卖
                    asset.Status = "FAS03";
                    DataAccess.Update(asset, broker);

                    //增加一笔历史记录
                    if (used != null)
                    {
                        FaUsedHistoryEntity history = new FaUsedHistoryEntity();
                        history.Id = Guid.NewGuid().ToString();
                        history.AssetId = asset.Id;
                        history.ApplicationId = null;
                        history.UsedType = "UT04";
                        history.DepartmentId = null;
                        history.PersonId = null;
                        history.FromDate = DateTime.Today;
                        //history.EndDate = DateTime.Today;
                        history.Remark = "固定资产变卖";
                        DataAccess.Insert(history, broker);
                    }

                    //更改固定资产所属情况
                    if (used != null)
                    {
                        used.ApplicationId = null;
                        used.DepartmentId = null;
                        used.PersonId = null;
                        used.FromDate = DateTime.Today;
                        used.Remark = "";
                        DataAccess.Update(used, broker);
                    }

                    //增加变卖信息
                    if (isNew)
                    {
                        DataAccess.Insert(salesInfo, broker);
                    }
                    else
                    {
                        DataAccess.Update(salesInfo, broker);
                    }

                    ////新增一条现金流数据
                    //FinCashFlowEntity cashFlow = new FinCashFlowEntity();
                    //cashFlow.CashFlowId = Guid.NewGuid().ToString();
                    //cashFlow.PeronId = salesInfo.SalePerson;
                    //cashFlow.Currency = "CS01";
                    //cashFlow.CashFlowType = "CFT50";
                    //cashFlow.AccountsCode = "1606";
                    //cashFlow.CashFlowDate = salesInfo.SaleDate;
                    //cashFlow.Amount = salesInfo.Price;
                    //cashFlow.Remark = "变卖固定资产所得金额";
                    //cashFlow.CreatedBy = salesInfo.SalePerson;
                    //cashFlow.CreatedDate = salesInfo.SaleDate;
                    //cashFlow.LastModifiedBy = salesInfo.SalePerson;
                    //cashFlow.LastModifiedDate = salesInfo.SaleDate;
                    //FinCashFlowBs.InsertCashFlow(cashFlow, broker);

                    broker.Commit();
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
            return true;
        }

        //固定资产删除
        public bool DelFaAsset(FaAssetsEntity asset)
        {
            if (asset == null)
                return false;
            try
            {
                List<FaAssetsEntity> list = new List<FaAssetsEntity>();
                GetAllChildAssets(asset, list);
                if (list.Count > 1)
                {
                    MyDebug.write("该固定资产存在配件，不能删除！");
                }
                DataAccess.Delete(asset);
                return true;
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return false;
            }
        }


        //分页查询固定资产保养信息
        public DataSet GetFaManufactureAllDsByCondition(ManufacturerQueryCondition con)
        {
            int pageIndex = 1;
            int pageSize = 50;
            if (con.txtPageIndex != 0)
                pageIndex = con.txtPageIndex;
            if (con.txtPageSize != 0)
                pageSize = con.txtPageSize;
            string condition = "";
            if (con.LastMaintainDate != null && con.LastMaintainDate!=new DateTime(1,1,1))
            {
                condition += " AND M.LAST_MAINTAIN_DATE >= CONVERT(DATETIME,'" + con.LastMaintainDate + "')";
            }
            if (con.LastMaintainDate != null && con.LastMaintainDate != new DateTime(1, 1, 1))
            {
                condition += " AND M.LAST_MAINTAIN_DATE <= CONVERT(DATETIME,'" + con.LastMaintainDateTo + "')";
            }
            if (!string.IsNullOrEmpty(con.AssetId))
            {
                condition += " AND M.ASSET_ID = '" + con.AssetId + "' ";
            }
            string sql = "";
            if (string.IsNullOrEmpty(condition))
            {
                string sqlSource = @"select top {0} *,(select count(1) from FA_ASSETS) as cnt
from FA_ASSETS
where id not in (
    select top ({1}*({2}-1)) id from FA_ASSETS order by created_date desc
) order by created_date desc";
                sqlSource = string.Format(sqlSource, pageSize, pageSize, pageIndex);
                sql = @"select A.*,M.*
from ({0}) A
LEFT JOIN FA_MANUFACTURER M ON M.ID = A.ID
WHERE A.NEED_MAINTENANCE = 1 ";
                sql = string.Format(sql, sqlSource);
            }
            else
            {
                sql = @"select top {0} *,(select count(1) from ({3}) t) as cnt
from ({3}) t
where t.id not in (
    select top ({1}*({2}-1)) id from ({3}) t order by created_date desc
) order by created_date desc";
                string sqlSource = @"select A.*, M.*
FROM FA_ASSETS A
LEFT JOIN FA_MANUFACTURER M ON M.ID = A.ID
WHERE A.NEED_MAINTENANCE = 1 ";
                sqlSource += condition;
                sql = string.Format(sql, pageSize, pageSize, pageIndex, sqlSource);
            }
            return DataAccess.SelectDataSet(sql);
        }

        //分页查询固定资产维修信息
        public DataSet GetFaRepairAllDsByCondition(FaRepairQueryCondition con)
        {
            int pageIndex = 1;
            int pageSize = 50;
            if (con.txtPageIndex != 0)
                pageIndex = con.txtPageIndex;
            if (con.txtPageSize != 0)
                pageSize = con.txtPageSize;
            string condition = "";
            if (con.LastMaintainDate != null && con.LastMaintainDate != new DateTime(1, 1, 1))
            {
                condition += " AND R.LAST_REPAIR_DATE >= CONVERT(DATETIME,'" + con.LastMaintainDate + "')";
            }
            if (con.LastMaintainDate != null && con.LastMaintainDate != new DateTime(1, 1, 1))
            {
                condition += " AND R.LAST_REPAIR_DATE <= CONVERT(DATETIME,'" + con.LastMaintainDateTo + "')";
            }
            if (!string.IsNullOrEmpty(con.AssetId))
            {
                condition += " AND R.ASSET_ID = '" + con.AssetId + "' ";
            }
            string sql = "";
            if (string.IsNullOrEmpty(condition))
            {
                string sqlSource = @"select top {0} *,(select count(1) from FA_ASSETS) as cnt
from FA_ASSETS
where id not in (
    select top ({1}*({2}-1)) id from FA_ASSETS order by created_date desc
) order by created_date desc";
                sqlSource = string.Format(sqlSource, pageSize, pageSize, pageIndex);
                sql = @"select A.*, R.*
from ({0}) A
 INNER JOIN FA_REPAIR R ON R.ID = A.ID
WHERE 1=1 ";
                sql = string.Format(sql, sqlSource);
            }
            else
            {
                sql = @"select top {0} *,(select count(1) from ({3}) t) as cnt
from ({3}) t
where t.id not in (
    select top ({1}*({2}-1)) id from ({3}) t order by created_date desc
) order by created_date desc";
                string sqlSource = @"select A.*, R.*
FROM FA_ASSETS A
 INNER JOIN FA_REPAIR R ON R.ID = A.ID
WHERE 1 = 1 ";
                sqlSource += condition;
                sql = string.Format(sql, pageSize, pageSize, pageIndex, sqlSource);
            }
            return DataAccess.SelectDataSet(sql);
        }

        //分页查询固定资产类型
        public DataSet GetFaAssetTypeAllDsByCondition(string condition, string orderBy, string rowCount)
        {
            string sql = CommonFunctions.GetSelect(rowCount) + @"AT1.*, AT2.ASSET_TYPE_CODE AS ASSET_TYPE_CODE2, AT2.ASSET_TYPE_NAME AS ASSET_TYPE_NAME2,
	                            AT3.ASSET_TYPE_CODE AS ASSET_TYPE_CODE3, AT3.ASSET_TYPE_NAME AS ASSET_TYPE_NAME3,
	                            AT4.ASSET_TYPE_CODE AS ASSET_TYPE_CODE4, AT4.ASSET_TYPE_NAME AS ASSET_TYPE_NAME4,
	                            AT5.ASSET_TYPE_CODE AS ASSET_TYPE_CODE5, AT5.ASSET_TYPE_NAME AS ASSET_TYPE_NAME5
                            FROM FA_ASSETS_TYPE AT1
                            LEFT JOIN FA_ASSETS_TYPE AT2 ON AT2.ID = AT1.PARENT_ID
                            LEFT JOIN FA_ASSETS_TYPE AT3 ON AT3.ID = AT2.PARENT_ID
                            LEFT JOIN FA_ASSETS_TYPE AT4 ON AT4.ID = AT3.PARENT_ID
                            LEFT JOIN FA_ASSETS_TYPE AT5 ON AT5.ID = AT4.PARENT_ID
                            WHERE 1=1 ";
            if (string.IsNullOrEmpty(condition) == false)
            {
                sql += condition;
            }
            if (string.IsNullOrEmpty(orderBy) == false)
            {
                sql += " ORDER BY " + orderBy;
            }
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null)
            {
                return ds;
            }
            return null;
        }

        //删除固定资产类型
        public bool DelFaAssetType(FaAssetsTypeEntity entity)
        {
            if (entity == null)
            {
                return false;
            }
            try
            {
                List<FaAssetsTypeEntity> list = new List<FaAssetsTypeEntity>();
                GetAllChildType(entity, list);
                DataAccess.Delete<FaAssetsTypeEntity>(list);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("RefFA_ASSETS_TYPE566"))
                {
                    throw new Exception("已经存在该类型的固定资产，不能删除！");
                }
                throw ex;
            }
            return true;
        }
        private void GetAllChildType(FaAssetsTypeEntity type, List<FaAssetsTypeEntity> list)
        {
            if (list.Count == 0)
            {
                list.Add(type);
            }
            List<FaAssetsTypeEntity> listChild = DataAccess.Select<FaAssetsTypeEntity>(new FaAssetsTypeEntity { ParentId = type.Id });
            if (listChild != null && listChild.Count > 0)
            {
                foreach (FaAssetsTypeEntity at in listChild)
                {
                    list.Add(at);
                    GetAllChildType(at, list);
                }
            }


        }


        //分页查询固定资产使用申请
        public DataSet GetFaAssetUseAppAllDsByCondition(FaUseAppQueryCondition con)
        {
            int pageIndex = 1;
            int pageSize = 50;
            if (con.txtPageIndex != 0)
                pageIndex = con.txtPageIndex;
            if (con.txtPageSize != 0)
                pageSize = con.txtPageSize;
            string condition = "";
            if (!string.IsNullOrEmpty(con.AppNo))
            {
                condition += " AND UA.APPLICATION_CODE LIKE '%" + con.AppNo + "%'";
            }
            if (con.AppDate != null && con.AppDate != new DateTime(1, 1, 1))
            {
                condition += " AND UA.APPLICATION_DATE >= CONVERT(DATETIME,'" + con.AppDate + "')";
            }
            if (con.AppDateTo != null && con.AppDateTo != new DateTime(1, 1, 1))
            {
                condition += " AND UA.APPLICATION_DATE <= CONVERT(DATETIME,'" + con.AppDateTo + "')";
            }
            if (!string.IsNullOrEmpty(con.DeptNo))
            {
                condition += " AND D.DEPARTMENT_ID = '" + con.DeptNo + "' ";
            }
            if (!string.IsNullOrEmpty(con.ApproveUserNo))
            {
                condition += " AND UA.APPROVED_PERSON = '" + con.ApproveUserNo + "' ";
            }
            if (!string.IsNullOrEmpty(con.Status))
            {
                condition += " AND UA.STATUS = '" + con.Status + "'";
            }

            string sql = "";
            if (string.IsNullOrEmpty(condition))
            {
                string sqlSource = @"select top {0} *,(select count(1) from FA_USED_APPLICATION) as cnt
from FA_USED_APPLICATION
where id not in (select top ({1}*({2}-1)) id from FA_USED_APPLICATION)";
                sqlSource = string.Format(sqlSource, pageSize, pageSize, pageIndex);
                sql = @"select UA.*, P1.firstName AS APPLICATION_PERSON_NAME, P2.firstName AS PERSON_NAME, 
D.departmentName,P3.firstName AS APPROVED_PERSON_NAME, FA.*
from ({0}) UA
LEFT JOIN BPMDB.dbo.PW_User P1 ON P1.userNo = UA.APPLICATION_PERSON
LEFT JOIN BPMDB.dbo.PW_User P2 ON P2.userNo = UA.PERSON_ID
LEFT JOIN BPMDB.dbo.PW_User P3 ON P3.userNo = UA.APPROVED_PERSON
LEFT JOIN BPMDB.dbo.PW_Department D ON D.departmentNo = UA.DEPARTMENT_ID
LEFT JOIN FA_ASSETS FA ON FA.ID = UA.ASSET_ID
WHERE FA.NEED_MAINTENANCE = 1 ";
                sql = string.Format(sql, sqlSource);
            }
            else
            {
                sql = @"select top {0} *,(select count(1) from ({3}) t) as cnt
from ({3}) t
where t.id not in (select top ({1}*({2}-1)) id from ({3}) t)";
                string sqlSource = @"select UA.*, P1.firstName AS APPLICATION_PERSON_NAME, P2.firstName AS PERSON_NAME, 
D.departmentName,P3.firstName AS APPROVED_PERSON_NAME, FA.*
FROM FA_USED_APPLICATION UA
LEFT JOIN BPMDB.dbo.PW_User P1 ON P1.userNo = UA.APPLICATION_PERSON
LEFT JOIN BPMDB.dbo.PW_User P2 ON P2.userNo = UA.PERSON_ID
LEFT JOIN BPMDB.dbo.PW_User P3 ON P3.userNo = UA.APPROVED_PERSON
LEFT JOIN BPMDB.dbo.PW_Department D ON D.departmentNo = UA.DEPARTMENT_ID
LEFT JOIN FA_ASSETS FA ON FA.ID = UA.ASSET_ID
WHERE 1 = 1 ";
                sqlSource += condition;
                sql = string.Format(sql, pageSize, pageSize, pageIndex, sqlSource);
            }
            return DataAccess.SelectDataSet(sql);
        }

        //固定资产使用申请更新
        public bool UpdateFaAssetUseApp(string userNo, FaUsedApplicationEntity entity)
        {
            try
            {
                return DataAccess.Update(entity);
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return false;
            }
        }

        //分页查询固定资产使用
        public DataSet GetFaAssetUseAllDsByCondition(FaUseQueryCondition con)
        {
            int pageIndex = 1;
            int pageSize = 50;
            if (con.txtPageIndex != 0)
                pageIndex = con.txtPageIndex;
            if (con.txtPageSize != 0)
                pageSize = con.txtPageSize;
            string condition = "";
            if (!string.IsNullOrEmpty(con.AssetTypeId))
            {
                condition += " AND (AT1.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT2.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT3.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT4.ASSET_TYPE_ID = '" + con.AssetTypeId + "' OR AT5.ASSET_TYPE_ID = '" + con.AssetTypeId + "') ";
            }
            if (!string.IsNullOrEmpty(con.Status))
            {
                condition += " AND A.STATUS = '" + con.Status + "' ";
            }
            if (string.IsNullOrEmpty(con.AssetNo) == false)
            {
                condition += " AND A.ASSET_CODE LIKE '%" + con.AssetNo + "%' ";
            }
            if (string.IsNullOrEmpty(con.AssetSpec) == false)
            {
                condition += " AND A.ASSET_SPEC = '" + con.AssetSpec + "' ";
            }
            if (string.IsNullOrEmpty(con.AssetName) == false)
            {
                condition += " AND A.ASSET_NAME LIKE '%" + con.AssetName + "%' ";
            }
            if (string.IsNullOrEmpty(con.UserNo) == false)
            {
                condition += " AND P.USER_NO = '" + con.UserNo + "' ";
            }

            string sql = "";
            if (string.IsNullOrEmpty(condition))
            {
                string sqlSource = @"select top {0} *,(select count(1) from FA_USED_APPLICATION) as cnt
from FA_USED_APPLICATION
where id not in (select top ({1}*({2}-1)) id from FA_USED_APPLICATION)";
                sqlSource = string.Format(sqlSource, pageSize, pageSize, pageIndex);
                sql = @"select UA.*,P1.firstName AS APP_USER,P2.firstName AS OWER_USER,P3.firstName AS APPROVED_USER
from ({0}) UA
LEFT JOIN BPMDB.dbo.PW_User P1 ON P1.userNo = UA.APPLICATION_PERSON
LEFT JOIN BPMDB.dbo.PW_User P2 ON P2.userNo = UA.PERSON_ID
LEFT JOIN BPMDB.dbo.PW_User P3 ON P3.userNo = UA.APPROVED_PERSON
LEFT JOIN BPMDB.dbo.PW_Department D ON D.departmentNo = UA.DEPARTMENT_ID
LEFT JOIN FA_ASSETS FA ON FA.ID = UA.ASSET_ID
WHERE 1 = 1 ";
                sql = string.Format(sql, sqlSource);
            }
            else
            {
                sql = @"select top {0} *,(select count(1) from ({3}) t) as cnt
from ({3}) t
where t.id not in (
    select top ({1}*({2}-1)) id from ({3}) t)";
                string sqlSource = @"select UA.*,P1.firstName AS APP_USER,P2.firstName AS OWER_USER,P3.firstName AS APPROVED_USER
FROM FA_USED_APPLICATION UA
LEFT JOIN BPMDB.dbo.PW_User P1 ON P1.userNo = UA.APPLICATION_PERSON
LEFT JOIN BPMDB.dbo.PW_User P2 ON P2.userNo = UA.PERSON_ID
LEFT JOIN BPMDB.dbo.PW_User P3 ON P3.userNo = UA.APPROVED_PERSON
LEFT JOIN BPMDB.dbo.PW_Department D ON D.departmentNo = UA.DEPARTMENT_ID
LEFT JOIN FA_ASSETS FA ON FA.ID = UA.ASSET_ID
WHERE 1 = 1 ";
                sqlSource += condition;
                sql = string.Format(sql, pageSize, pageSize, pageIndex, sqlSource);
            }
            return DataAccess.SelectDataSet(sql);
        }


        //归还固定资产
        public bool ReturnFaAsset(string userNo, FaAssetsEntity asset)
        {
            FaUsedEntity used = DataAccess.SelectSingle<FaUsedEntity>(new FaUsedEntity { Id = asset.Id });
            if (used == null)
            {
                MyDebug.write("找不到该固定资产的使用信息，无法归还");
                return false;
            }
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();

                    //设置固定资产状态为空闲
                    asset.Status = "FAS01";
                    DataAccess.Update(asset, broker);

                    //增加一笔历史记录
                    FaUsedHistoryEntity history = new FaUsedHistoryEntity();
                    history.Id = Guid.NewGuid().ToString();
                    history.AssetId = asset.Id;
                    history.ApplicationId = null;
                    history.UsedType = "UT02";
                    history.DepartmentId = used.DepartmentId;
                    history.PersonId = used.PersonId;
                    history.FromDate = DateTime.Today;
                    //history.EndDate = DateTime.Today;
                    history.Remark = "归还固定资产";
                    DataAccess.Insert(history, broker);

                    //更改固定资产所属情况
                    used.ApplicationId = null;
                    used.DepartmentId = null;
                    used.PersonId = null;
                    used.FromDate = DateTime.Today;
                    used.Remark = "";
                    DataAccess.Update(used, broker);

                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    MyDebug.write(ex.Message);
                    return false;
                }
            }
        }
        
        //报废固定资产
        public bool ScrapAsset(string userNo, FaAssetsEntity asset)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();

                    //设置固定资产状态为已报废
                    asset.Status = "FAS04";
                    DataAccess.Update(asset, broker);

                    //增加一笔历史记录
                    FaUsedHistoryEntity history = new FaUsedHistoryEntity();
                    history.Id = Guid.NewGuid().ToString();
                    history.AssetId = asset.Id;
                    history.ApplicationId = null;
                    history.UsedType = "UT05";
                    history.DepartmentId = null;
                    history.PersonId = null;
                    history.FromDate = DateTime.Today;
                    //history.EndDate = DateTime.Today;
                    history.Remark = "固定资产报废";
                    DataAccess.Insert(history, broker);

                    //更改固定资产所属情况
                    FaUsedEntity used = DataAccess.SelectSingle<FaUsedEntity>(new FaUsedEntity { Id = asset.Id });
                    if (used != null)
                    {
                        used.ApplicationId = null;
                        used.DepartmentId = null;
                        used.PersonId = null;
                        used.FromDate = DateTime.Today;
                        used.Remark = "";
                        DataAccess.Update(used, broker);
                    }

                    broker.Commit();
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
            return true;
        }

        public FaUsedEntity GetFaUsedByKey(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                    return null;
                return DataAccess.SelectSingle<FaUsedEntity>(new FaUsedEntity { Id = id });
            }
            catch (Exception ex)
            {
                MyDebug.write(ex.Message);
                return null;
            }
        }

    }
}
